import Radio from 'backbone.radio';
import Mn from 'backbone.marionette';
import ChapterModel from 'task/models/price_study/ChapterModel.js';
import ProductModel from 'task/models/price_study/ProductModel.js';
import WorkModel from 'task/models/price_study/WorkModel.js';
import DiscountModel from 'task/models/price_study/DiscountModel.js';
import WorkItemModel from 'task/models/price_study/WorkItemModel';
import {
    ajax_call
} from 'tools';


const Controller = Mn.Object.extend({
    initialize(options) {
        this.facade = Radio.channel('facade');
        this.config = Radio.channel('config');
        this.rootView = options['rootView'];
        this.priceStudy = options['priceStudy'];
        this.chapters = options['chapters'];
    },
    index() {
        this.rootView.index();
    },
    showModal(view) {
        this.rootView.showModal(view);
    },
    // Chapter related views
    addChapter() {
        const collection = this.chapters;
        let options = {
            order: collection.getMaxOrder() + 1,
            display_details: true,
        }
        let model = new ChapterModel(options);
        this.rootView.showAddChapterForm(model, collection);
    },
    editChapter(chapterId) {
        const model = this.chapters.get(chapterId);
        this.rootView.showEditChapterForm(model, this.chapters);
    },
    // Product related views
    addProduct(chapterId) {
        const chapterModel = this.chapters.get(chapterId);
        const collection = chapterModel.products;
        let defaults = {
            order: collection.getMaxOrder() + 1,
            chapter_id: chapterId
        }
        Object.assign(defaults, this.productDefaults);
        let model = new ProductModel(defaults);
        this.rootView.showAddProductForm(model, collection);
    },
    editProduct(chapterId, modelId) {
        const chapterModel = this.chapters.get(chapterId);
        const collection = chapterModel.products;
        let request = collection.fetch();
        request = request.then(function () {
            let model = collection.get(modelId);
            return model;
        });
        request.then(this.rootView.showEditProductForm.bind(this.rootView));
    },
    duplicateProduct(model, chapterId) {
        let request = model.duplicate();
        var this_ = this;
        request.done(
            function (model) {
                let route;
                if (model.get('type_') == 'price_study_work') {
                    route = "chapters/" + chapterId + "/works/";
                    this_.rootView.showEditWorkForm(model);
                } else {
                    route = "chapters/" + chapterId + "/products/";
                    this_.rootView.showEditProductForm(model);
                }
                const dest_route = route + model.get('id');
                window.location.hash = dest_route;
            }
        );
    },
    insertFromCatalog(collection, sale_products) {
        let url = _.result(collection, 'url');
        url += "?action=load_from_catalog";
        let serverRequest = ajax_call(
            url, {
                sale_products: sale_products,
            },
            'POST'
        );
        return serverRequest.then(
            (models) => {
                this.facade.trigger('task:changed');
                return collection.fetch().then(() => models)
            }
        );
    },
    // Work related views
    addWork(chapterId) {
        const chapterModel = this.chapters.get(chapterId);
        const collection = chapterModel.products;
        let defaults = {
            order: collection.getMaxOrder() + 1
        }
        let model = new WorkModel(defaults);
        this.rootView.showAddWorkForm(model, collection);
    },
    editWork(chapterId, modelId) {
        const chapterModel = this.chapters.get(chapterId);
        const collection = chapterModel.products;
        let request = collection.fetch();
        request = request.then(function () {
            let model = collection.get(modelId);
            return model;
        });
        request.then(this.rootView.showEditWorkForm.bind(this.rootView));
    },
    addWorkItem(workModel) {
        const collection = workModel.items;
        let defaults = {
            order: collection.getMaxOrder() + 1
        }
        if (workModel.get('margin_rate')) {
            defaults['margin_rate_editable'] = false;
        }
        let model = new WorkItemModel(defaults);
        this.rootView.showAddWorkItemForm(model, collection);
    },
    // WorkItem 
    editWorkItem(model) {
        this.rootView.showEditWorkItemForm(model);
    },
    duplicateWorkItem(model) {
        let request = model.duplicate();
        request.done((model) => this.rootView.showEditWorkItemForm(model));
    },
    // Remise : Discount
    addDiscount() {
        const collection = this.facade.request('get:collection', 'discounts');
        let model = new DiscountModel({
            order: collection.getMaxOrder() + 1,
            type_: 'amount'
        });
        this.rootView.showAddDiscountForm(model, collection);
    },
    editDiscount(modelId) {
        let collection = this.facade.request('get:collection', 'discounts');
        let request = collection.fetch();
        request = request.then(function () {
            let model = collection.get(modelId);
            return model;
        });
        request.then(this.rootView.showEditDiscountForm.bind(this.rootView));
    },
    // Common model views
    _onModelDeleteSuccess: function () {
        let messagebus = Radio.channel('message');
        messagebus.trigger('success', this, "Vos données ont bien été supprimées");
        this.rootView.index();
    },
    _onModelDeleteError: function () {
        let messagebus = Radio.channel('message');
        messagebus.trigger('error', this,
            "Une erreur a été rencontrée lors de la " +
            "suppression de cet élément");
    },
    modelDelete(model) {
        var confirm = window.confirm("Êtes-vous sûr de vouloir supprimer cet élément ?");
        let promise;
        if (confirm) {
            promise = model.destroy({
                success: this._onModelDeleteSuccess.bind(this),
                error: this._onModelDeleteError.bind(this),
                wait: true
            });
        }
        return promise;
    },
    moveUp(model) {
        const promise = model.collection.moveUp(model);
        promise.then(() => this.index());
    },
    moveDown(model) {
        const promise = model.collection.moveDown(model)
        promise.then(() => this.index());
    },
    resetMarginRate() {
        let url = _.result(this.priceStudy, 'url');
        url += "?reset_margin_rate";
        const request = ajax_call(url, {}, 'POST');
        request.then(this.chapters.fetch());
    }
});
export default Controller;